import win32com.client
import os

def get_xlspw(xls,filename,password,several):
    
    try:
        if several:
            password=str(password).zfill(int(several))
        exceldoc = xls.Workbooks.Open(filename, False, True, None, Password=password)
        print('破解成功!')
        print("文档密码是：{}".format(password))
        exceldoc.Close()
        return True
    except:
        print(password)
        return False

def get_docpw(xls,filename,password,several):
        
    try:
        
        if several:
            password=str(password).zfill(int(several))
        else:
            password=str(password)
        wordoc=xls.Documents.Open(filename, False, True, None,PasswordDocument=password)
        print('破解成功!')
        print("文档密码是：{}".format(password))
        wordoc.Close()
        return True
    except:
        print(password)
        return False
    

def getpw_run(ftype,fname,p,several=None):
    
    if ftype=='excel':
        if os.path.exists(fname):
            if '.xls' in fname or '.xlsx' in fname:
                xls = win32com.client.Dispatch("Excel.Application")
                xls.Visible=0
                xls.DisplayAlerts=0
                if several:
                    p=p.zfill(int(several))
                print('破解中......')
                
                while True:

                    isdone=get_xlspw(xls,fname,p,several)
                    p=int(p)+1
                    if isdone:
                        break
                os.system('pause')
                    
                    
                        
            else:
                print('文档类型不正确')
                os.system('pause')
        else:
            print('文档路径不存在')
            os.system('pause')

    if ftype=='word':
        if os.path.exists(fname):
            if '.doc' in fname or '.docx' in fname:
                docx = win32com.client.Dispatch("Word.Application")
                ##如果是wps visible=1
                docx.Visible=0
                docx.DisplayAlerts=0
                if several:
                    p=p.zfill(int(several))
                print('破解中......')
                        
                while True:
                        isdone=get_docpw(docx,fname,p,several)
                        p=int(p)+1
                        if isdone:
                            break
                os.system('pause')
                            
            else:
                print('文档类型不正确')
                os.system('pause')
        else:
            print('文档路径不存在')
            os.system('pause')
        
    

if __name__=='__main__':
    filetype=input('文档类型(excel,word)：')
    filename=input('文档路径：')
    pw=input('开始数：')
    digit=input('共多少位(需要前面补0就输入)：')
    getpw_run(filetype,filename,pw,digit)
   






  
        
